package com.kai.mqtt.config;

import com.kai.mqtt.data.Result;
import com.kai.mqtt.enums.ErrorCodeEnum;
import com.kai.mqtt.exception.BusinessException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.ConversionNotSupportedException;
import org.springframework.beans.TypeMismatchException;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.http.converter.HttpMessageNotWritableException;
import org.springframework.validation.FieldError;
import org.springframework.validation.ObjectError;
import org.springframework.web.HttpMediaTypeNotAcceptableException;
import org.springframework.web.HttpMediaTypeNotSupportedException;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.ServletRequestBindingException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.multipart.support.MissingServletRequestPartException;
import org.springframework.web.servlet.NoHandlerFoundException;

import java.util.List;

/**
 * 全局异常拦截处理器
 */
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    @ExceptionHandler(IllegalArgumentException.class)
    public <T> Result<T> illegalArgs(IllegalArgumentException e) {
        log.error("parameters check failed, failed msg: {}", e.getMessage(), e);
        return Result.fail(ErrorCodeEnum.PARAMETER_ERROR);
    }

    @ExceptionHandler(Exception.class)
    public <T> Result<T> handleException(Exception e) {
        log.error(e.getMessage(), e);
        return Result.fail(ErrorCodeEnum.BASE_ERROR);
    }

    @ExceptionHandler({HttpRequestMethodNotSupportedException.class,
            HttpMediaTypeNotSupportedException.class, HttpMediaTypeNotAcceptableException.class, MissingServletRequestParameterException.class,
            ServletRequestBindingException.class, ConversionNotSupportedException.class, TypeMismatchException.class,
            HttpMessageNotReadableException.class, HttpMessageNotWritableException.class,
            MissingServletRequestPartException.class, NoHandlerFoundException.class})
    public <T> Result<T> handleRequestParserException(Exception e) {
        log.error(e.getMessage(), e);
        return Result.fail(ErrorCodeEnum.PARAMETER_ERROR.getCode(), ErrorCodeEnum.PARAMETER_ERROR.getMsg() + ":" + e.getMessage());
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public <T> Result<T> handleMethodArgumentNotValidException(MethodArgumentNotValidException e) {
        log.error(e.getMessage(), e);
        StringBuilder returnError = new StringBuilder();
        List<ObjectError> errors = e.getBindingResult().getAllErrors();
        if (!errors.isEmpty()) {
            for (ObjectError error : errors) {
                FieldError fieldError = (FieldError) error;
                String field = fieldError.getField();
                returnError.append(field).append("(").append(fieldError.getDefaultMessage()).append(");");
            }
        }
        return Result.fail(ErrorCodeEnum.PARAMETER_ERROR.getCode(), ErrorCodeEnum.PARAMETER_ERROR.getMsg() + ":" + returnError);
    }

    @ExceptionHandler(BusinessException.class)
    public <T> Result<T> handleBusinessException(BusinessException e) {
        // 获取到堆栈信息
        StackTraceElement[] stackTrace = e.getStackTrace();
        StackTraceElement stackTraceElement = stackTrace[0];
        log.error("[BusinessException] ERROR MESSAGE: {}\n" +
                        "    at {}.{}({}:{})",
                e.getMessage(),
                stackTraceElement.getClassName(),
                stackTraceElement.getMethodName(),
                stackTraceElement.getFileName(),
                stackTraceElement.getLineNumber());
        return Result.fail(e.getErrorCode(), e.getMessage());
    }

}
